<template>
  <RjModal
    width="600px"
    :title="modalTitle"
    :visible="isVisible"
    @ok="onSave"
    @cancel="onCancel"
    :confirmLoading="isLoading"
  >
    <a-form-model
      ref="deviceFormRef"
      :model="deviceForm"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }"
      labelAlign="left"
      :colon="false"
      :rules="formRuleObj"
    >
      <a-form-model-item :label="$t('common.deviceName')" prop="deviceName">
        <a-input v-model="deviceForm.deviceName" />
      </a-form-model-item>
      <a-form-model-item :label="$t('authLog.devGroup')" prop="areaId">
        <a-select v-model="deviceForm.areaId">
          <div slot="dropdownRender" slot-scope="menu">
            <v-nodes :vnodes="menu" />
            <a
              style="padding: 4px 8px 8px; cursor: pointer; display: block"
              @mousedown="(e) => e.preventDefault()"
              @click="onAddGroup"
            >
              <icon-font type="ic-plus" />
              {{ $t('authDevice.addGroup') }}
            </a>
          </div>
          <a-select-option
            v-for="item in deviceGroups"
            :key="item.id"
            :title="item.name"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('common.deviceType')" prop="modelType">
        <a-select v-model="deviceForm.modelType" :options="deviceTypeOptions">
        </a-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('authDevice.ipAndRange')" prop="ip">
        <a-input
          autocomplete="new-password"
          v-model="deviceForm.ip"
          :placeholder="$t('validateTools.ipAndSegTip')"
        />
      </a-form-model-item>
      <a-form-model-item
        :label="$t('authDevice.radiusSecret')"
        prop="radiusKey"
      >
        <a-input-password
          :maxLength="32"
          v-model="deviceForm.radiusKey"
          autocomplete="new-password"
          :placeholder="$t('authDevice.dot1xTip')"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('authDevice.devSn')">
        <a-input
          :maxLength="32"
          v-model="deviceForm.serialNumber"
          :placeholder="$t('authDevice.portalTip')"
        />
      </a-form-model-item>
      <a-form-model-item prop="mac">
        <a-space slot="label" :size="4">
          {{ $t('authDevice.devMac') }}
          <a-tooltip>
            <template slot="title">
              {{ $t('authDevice.macTip') }}
            </template>
            <icon-font type="ic-help" />
          </a-tooltip>
        </a-space>
        <a-input
          v-model="deviceForm.mac"
          :placeholder="$t('authDevice.dot1xTip2')"
        />
      </a-form-model-item>
    </a-form-model>
  </RjModal>
</template>

<script>
import { requestHttp, maccApi } from '@utils/index';
import { mapState } from 'vuex';
import { ValiDateTools } from '@/utils/validateTools';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
export default {
  name: 'authDeviceModal',
  mixins: [authSysMixin],
  props: {
    deviceGroupId: {
      type: Number,
      default: 0,
    },
  },
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  data() {
    return {
      operation: 'add',
      isLoading: false,
      deviceForm: {
        deviceName: '',
        areaId: '',
        modelType: 'ap',
        ip: '',
        radiusKey: '',
        mac: '',
        serialNumber: '',
      },
      formRuleObj: {
        deviceName: [
          {
            required: true,
            message: this.$t('common.mustEnter'),
            trigger: 'blur',
          },
          { validator: this.validDeviceName, trigger: 'blur' },
        ],
        areaId: [
          {
            required: true,
            message: this.$t('common.mustEnter'),
            trigger: 'change',
          },
        ],
        modelType: [
          {
            required: true,
            message: this.$t('common.mustEnter'),
            trigger: 'change',
          },
        ],
        ip: [
          {
            required: true,
            message: this.$t('common.mustEnter'),
            trigger: 'blur',
          },
          { validator: this.validDeviceIp, trigger: 'blur' },
        ],
        mac: [{ validator: this.validDeviceMac, trigger: 'blur' }],
      },
      isVisible: false,
    };
  },

  mounted() {},
  computed: {
    ...mapState('AuthCommon', ['deviceGroups', 'deviceTypes']),
    modalTitle() {
      if (this.operation === 'add') {
        return this.$t('authDevice.addDev');
      } else {
        return this.$t('authDevice.editDev');
      }
    },
    deviceTypeOptions() {
      const tempOptions = [];
      for (const devType of this.deviceTypes) {
        tempOptions.push({
          label: devType.value,
          value: devType.key,
        });
      }
      return tempOptions;
    },
    deviceGroupMap() {
      const tempMap = {};
      for (const group of this.deviceGroups) {
        tempMap[group.id] = group;
      }
      return tempMap;
    },
  },
  methods: {
    onAddGroup() {
      this.$emit('addDeviceGroup');
    },
    resetForm() {
      this.deviceForm = {
        deviceName: '',
        areaId: '',
        modelType: 'ap',
        ip: '',
        radiusKey: '',
        mac: '',
        serialNumber: '',
      };
    },
    setGroupId(groupId) {
      this.deviceForm.areaId = groupId;
    },
    validDeviceName(rule, value, callback) {
      if (!value) {
        return callback(new Error(this.$t('common.mustEnter')));
      }
      const len = value.replace(/[^\x00-\xff]/g, '|||').length;
      if (len > 32) {
        return callback(new Error(this.$t('common.byteRange1To32AndChinese')));
      }
      callback();
    },

    // 校验IP
    validDeviceIp(rule, value, callback) {
      const ipRes = ValiDateTools.checkIpOnEweb(value);
      const ipSegRes = ValiDateTools.checkIpSegment(value);
      if (!ipRes.result && !ipSegRes.result) {
        return callback(new Error(this.$t('validateTools.ipAndSegTip')));
      }
      callback();
    },

    // 校验MAC
    validDeviceMac(rule, value, callback) {
      if (!value) {
        return callback();
      }
      const { result, msg } = ValiDateTools.checkMac(value);
      if (!result) {
        return callback(new Error(msg));
      }

      callback();
    },

    openModal(record) {
      this.isVisible = true;

      if (record) {
        this.operation = 'edit';
        this.deviceForm = { ...record };
      } else {
        this.operation = 'add';
        if (this.deviceGroupId) {
          this.deviceForm.areaId = this.deviceGroupId;
        }
      }
    },

    // 弹窗 确认
    onSave() {
      this.$refs.deviceFormRef.validate(async (valid) => {
        if (!valid) {
          return false;
        }
        this.saveDevice();
      });
    },

    async saveDevice() {
      this.isLoading = true;

      let api = '';
      let method = '';
      let params = { ...this.deviceForm };
      let successTxt = '';
      if (this.operation === 'add') {
        api = maccApi.PRIVATE_DEVICE_ADD_POST_API;
        method = 'POST';
        successTxt = this.$t('common.addSuceess');
      } else {
        api = maccApi.PRIVATE_DEVICE_UPDATE_PUT_API;
        method = 'PUT';
        successTxt = this.$t('common.editSuccess');
      }

      const res = await this.requestHttpAuth({
        api,
        method,
        params,
      });
      this.isLoading = false;
      if (res.data.success) {
        this.isVisible = false;
        this.resetForm();
        this.$emit('refreshList');
        this.$message.success(successTxt);
      } else {
        this.$message.warning(res.data.message);
      }
    },

    // 弹窗 取消
    onCancel() {
      this.isLoading = false;
      this.isVisible = false;
      this.resetForm();

      // // 更新serverGrp配置
      // this.callbackAfterClose && this.callbackAfterClose();
    },
  },
};
</script>

<style lang="less" scoped>
@import url('@/project/authSys/assets/skin/common.less');
</style>
